<template>
  <div class="mod-log">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-input v-model="dataForm.id" placeholder="文件id" clearable></el-input>
      </el-form-item>
        <el-form-item>
        <el-input v-model="dataForm.fileName" placeholder="文件名" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-select v-model="dataForm.fileType" placeholder="请选择文件分类" clearable filterable>
          <el-option
                v-for="item in fileTypeList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">检索</el-button>
        <el-button type="success" @click="exportExcel()">导出</el-button>
        <el-button type="danger"  @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%">
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>
      <el-table-column
        label="序号"
        type="index"
        width="50">
      </el-table-column>
      <el-table-column
        prop="id"
        header-align="center"
        align="center"
        width="150"
        :show-overflow-tooltip="true"
        label="文件id">
      </el-table-column>
      <el-table-column
        prop="fileName"
        header-align="center"
        align="center"
        width="150"
        label="文件名">
      </el-table-column>
      <el-table-column
        prop="fileSize"
        header-align="center"
        align="center"
        width="80"
        label="文件大小">
      </el-table-column>
        <el-table-column
        prop="fileType"
        header-align="center"
        align="center"
        width="80"
        label="文件分类">
         <template slot-scope="scope">
           <span v-if="scope.row.fileType === 0">数据文件</span>
           <span v-if="scope.row.fileType === 1">图像文件</span>
           <span v-if="scope.row.fileType === 2">视频文件</span>
           <span v-if="scope.row.fileType === 3">论文文件</span>
           <span v-if="scope.row.fileType === 4">各类电子文书</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="fileStatus"
        header-align="center"
        align="center"
        width="150"
        label="是否共享">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.fileStatus === 1" size="small" type="info">私有</el-tag>
          <el-tag v-else size="small">共享</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="fileTheme"
        header-align="center"
        align="center"
        width="130"
        :show-overflow-tooltip="true"
        label="研究主题">
      </el-table-column>
      <el-table-column
        prop="createUserName"
        header-align="center"
        align="center"
        width="130"
        label="上传用户">
      </el-table-column>
      <el-table-column
        prop="createTime"
        header-align="center"
        align="center"
        width="180"
        label="上传时间"
        :formatter="formateCreateTime">
      </el-table-column>
      <el-table-column
        header-align="center"
        fixed="right"
        align="center"
        width="150"
        label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="download(scope.row)">阅览1</el-button>
          <el-button type="text" size="small" @click="open(scope.row)">阅览2</el-button>
          <el-button type="text" size="small" @click="addNotes(scope.row)">添加笔记</el-button>
          <el-button type="text" size="small" @click="update(scope.row)">修改</el-button>
          <el-button type="text" size="small"  @click="deleteHandle(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"download
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>

     <el-dialog
      :title="'输入密码'"
      :close-on-click-modal="false"
      :visible.sync="passwordVisible"
      :before-close="canclePassword"
      width="25%">

      <el-form :model="passwordForm"  :rules="passwordRule" ref="passwordForm" @keyup.enter.native="submitPassword()"
               label-width="80px">
        <el-form-item label="文件密码" prop="filePassword">
          <el-input v-model="passwordForm.filePassword"  placeholder="请输入文件密码" ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="canclePassword">取消</el-button>
        <el-button type="primary" @click="submitPassword()">确定</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>
import ueditor from 'ueditor'
  export default {
    data () {
      return {
        dataForm: {
          referenceDictId: '',
          publishAuthor: '',
          referenceTitle: '',
          id: ''
        },
        ue: null,
        ueId: `J_ueditorBox_${new Date().getTime()}`,
        ueContent: '',
        passwordForm:{
          filePassword: ''
        },
        addNotesForm: {
          fileId: '',
          fileName: '',
          content: ''
        },
        fileTypeList: [{
          id: 0,
          name: '数据文件'
        }, {
          id: 1,
          name: '图像文件'
        }, {
          id: 2,
          name: '视频文件'
        }, {
          id: 3,
          name: '论文文件'
        }, {
          id: 4,
          name: '各类电子文书'
        }],
        iconSuccessName: 'collected',
        referenceDictList: [],
        downloadId: '',
        dataList: [],
        dataListSelections: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        passwordVisible: false,
        selectionDataList: [],
        passwordRule: {
        filePassword: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ]}
      }
    },
    created () {
      //this.getReferenceDictList()
      this.getDataList()
    },
    mounted () {
      this.ue = ueditor.getEditor(this.ueId, {
        serverUrl: 'http://www.baidu.com', // 服务器统一请求接口路径
        zIndex: 3000
      })
    },
    methods: {
      open(row) {
        this.downloadId = row.id
        if(row.filePassword){
          this.passwordVisible = true;
        }else{
          this.review1(row.id,'')
        }
      },
      dateFormat() {
          var date=new Date();
          var year=date.getFullYear();
          /* 在日期格式中，月份是从0开始的，因此要加0
            * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
            * */
          var month= date.getMonth()+1<10 ? "0"+(date.getMonth()+1) : date.getMonth()+1;
          var day=date.getDate()<10 ? "0"+date.getDate() : date.getDate();
          var hours=date.getHours()<10 ? "0"+date.getHours() : date.getHours();
          var minutes=date.getMinutes()<10 ? "0"+date.getMinutes() : date.getMinutes();
          var seconds=date.getSeconds()<10 ? "0"+date.getSeconds() : date.getSeconds();
          // 拼接
          return year+"-"+month+"-"+day+" "+hours+":"+minutes+":"+seconds;
      },
      exportExcel () {
        this.$http({
          url: this.$http.adornUrl('/fileManage/export'),
          method: 'post',
          data: this.$http.adornData({
            'fileName': this.dataForm.fileName,
            'fileType': this.dataForm.fileType,
            'id': this.dataForm.id,
            'pageNum': this.pageIndex,
            'pageSize': this.pageSize
          }),
          responseType: 'arraybuffer'
        }).then(({data, headers}) => {
          const link = document.createElement('a'); // 生成一个a标签。
          let blob = new Blob([data], {type: "application/vnd.ms-excel"});
          let objectUrl = URL.createObjectURL(blob);
          link.href = objectUrl
          let title = headers['filename']
          let timeStr = this.dateFormat
          link.download = decodeURI(title) // 自定义文件名
          link.click() // 下载文件
          URL.revokeObjectURL(objectUrl); // 释放内存
        })
      },
      addNotes(row) {
        this.$router.push({path:'demo-ueditor',query: {row:row}})
      },
      // 多选
      selectionChangeHandle(val) {
        this.dataListSelections = val
      },
      // 删除
      deleteHandle(id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.id
        })
        this.$confirm(`确定要进行删除操作吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/fileManage/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 200) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }).catch(() => {
        })
      },
      submitPassword () {
        let id = this.downloadId
        let filePassword = this.passwordForm.filePassword
        this.review(id,filePassword)

      },
      canclePassword () {
        this.passwordVisible = false
        this.$refs['passwordForm'].resetFields()
        this.downloadId = ''
      },
      update (row) {
          this.$router.push({path:'document-upload',query: {row:row}})
      },
      download (row) {
        this.downloadId = row.id
        if(row.filePassword){
          this.passwordVisible = true;
        }else{
          this.review(row.id,'')
        }
      },
      review1 (id,filePassword) {
        this.$http({
          url: this.$http.adornUrl('/fileManage/review'),
          method: 'post',
          data: this.$http.adornData({
            'id': id,
            'filePassword':filePassword
          })
        }).then(({data}) => {
          if (data && data.code === 200) {
            debugger
            let url = data.data.fileUrl
            window.open(url, '_blank')
            if(filePassword){
              this.canclePassword()
            }else{
              this.downloadId = ''
            }
          }else{
            this.$message.error(data.msg)
          }
        })
      },
      review (id,filePassword) {
        this.$http({
          url: this.$http.adornUrl('/fileManage/review'),
          method: 'post',
          data: this.$http.adornData({
            'id': id,
            'filePassword':filePassword
          })
        }).then(({data}) => {
          if (data && data.code === 200) {
            debugger
            let url = data.data.filePath
            console.log(url)
            window.open(url, '_blank')
            if(filePassword){
              this.canclePassword()
            }else{
              this.downloadId = ''
            }
          }else{
            this.$message.error(data.msg)
          }
        })
      },
      formateCreateTime (row, column) {
        var objD = row.createTime
        if (!objD) {
          return ''
        }
        objD = new Date(objD)
        var str
        var yy = objD.getYear()
        if (yy < 1900) yy = yy + 1900
        var MM = objD.getMonth() + 1
        if (MM < 10) MM = '0' + MM
        var dd = objD.getDate()
        if (dd < 10) dd = '0' + dd
        var hh = objD.getHours()
        if (hh < 10) hh = '0' + hh
        var mm = objD.getMinutes()
        if (mm < 10) mm = '0' + mm
        var ss = objD.getSeconds()
        if (ss < 10) ss = '0' + ss
        str = yy + '-' + MM + '-' + dd + ' ' + hh + ':' + mm + ':' + ss
        return (str)
      },
      // 获取数据列表
      getDataList () {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/fileManage/list'),
          method: 'post',
          data: this.$http.adornData({
            'fileName': this.dataForm.fileName,
            'fileType': this.dataForm.fileType,
            'id': this.dataForm.id,
            'pageNum': this.pageIndex,
            'pageSize': this.pageSize
          })
        }).then(({data}) => {
          if (data && data.code === 200) {
            this.dataList = data.data.records
            // this.dataList.forEach((item) => {
            //   item.timeMs = item.time + 'ms'
            // })
            this.totalPage = data.data.total
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      }
    }
  }
</script>
<style lang="scss">
  .mod-demo-ueditor {
    position: relative;
    z-index: 510;
    > .el-alert {
      margin-bottom: 10px;
    }
  }
</style>
